<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="驱动编码" prop="driveCode">
        <el-input
          v-model="queryParams.driveCode"
          placeholder="请输入驱动编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="驱动名称" prop="driveName">
        <el-input
          v-model="queryParams.driveName"
          placeholder="请输入驱动名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="插件库名称" prop="adapterName">
        <el-input
          v-model="queryParams.adapterName"
          placeholder="请输入插件库名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['device:drive:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['device:drive:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['device:drive:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['device:drive:import']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['device:drive:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="driveList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="驱动编码" align="center" prop="driveCode" width="190"/>
      <el-table-column label="驱动名称" align="center" prop="driveName"/>
      <el-table-column label="插件库名称" align="center" prop="adapterName"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-cooperation"
            @click="navToAdapterManagement(scope.row)"
            v-hasPermi="['device:drive:adapterManagement']"
          >插件库版本管理
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:drive:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:drive:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改模块对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="驱动编码" prop="driveCode" v-if="form.id">
          <el-input v-model="form.driveCode" disabled/>
        </el-form-item>
        <el-form-item label="驱动名称" prop="driveName">
          <el-input v-model="form.driveName" placeholder="请输入驱动名称"/>
        </el-form-item>
        <el-form-item label="插件库名称" prop="adapterName">
          <el-input v-model="form.adapterName" placeholder="请输入插件库名称"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  删除模块失败提示-->
    <el-dialog
      :visible.sync="deleteFailedDialogVisible"
      top="100px !important"
      width="800px"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      z-index="1002"
    >
      <template slot="title">
        提示：<span class="tip" style="color: red">驱动被以下模块引用，若要删除，请先从模块管理界面解绑模块对应的驱动！</span>
      </template>
      <el-table :data="driveInUsedList" max-height="600px">
        <el-table-column property="code" label="模块编码" width="190" align="center"/>
        <el-table-column property="name" label="模块名称" align="center"/>
        <el-table-column property="deleteDriveCode" label="引用驱动编码" width="190" align="center"/>
        <el-table-column property="deleteadapterName" label="引用驱动名称" align="center"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="small" type="primary" @click="navToDeviceModuleUnbind(scope.row)">去解绑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deleteFailedDialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>

    <!--  导入文件-->
    <import-file-dialog
      v-model="uploadDialogVisible"
      templateFileName="驱动信息导入模板"
      uploadApi="/device/drive/import"
      templateDownloadUrl="/device/drive/export"
      @onSuccess="handleUploadFileSuccess"
    />

  </div>
</template>

<script>
import {listDrive, getDrive, delDrive, addDrive, updateDrive} from "@/api/device/drive";

export default {
  name: "Drive",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 驱动表格数据
      driveList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        driveName: null,
        adapterName: null,
        driveCode: null,
        status: 0,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        driveName: [
          {required: true, message: "驱动名称不能为空", trigger: "blur"}
        ],
        adapterName: [
          {required: true, message: "插件库名称不能为空", trigger: "blur"}
        ],
      },
      // 设备被引用中弹窗
      deleteFailedDialogVisible: false,
      // 驱动被模块引用列表
      driveInUsedList: [],
      // 导入文件弹窗
      uploadDialogVisible: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 跳转到插件库管理页面
    navToAdapterManagement(row){
      this.$router.push({
        name: 'AdapterManagement',
        query: {
          driveName: row.driveName,
          adapterName: row.adapterName
        }
      })
    },
    // 导入文件上传成功
    handleUploadFileSuccess(res) {
      if (res.data === "上传成功！") this.getList()
    },
    handleImport() {
      this.uploadDialogVisible = true
    },
    // 跳转到模块管理页面解绑
    navToDeviceModuleUnbind(row) {
      this.deleteFailedDialogVisible = false;
      this.$router.push({
        path: '/device/deviceModule',
        query: {driveCode: row.deleteDriveCode}
      })
    },
    /** 查询模块列表 */
    getList() {
      this.loading = true;
      listDrive(this.queryParams).then(response => {
        this.driveList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        status: 0,//新增窗口打开时 状态默认正常
        driveCode: null,
        driveName: null,
        adapterName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加模块";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDrive(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改模块";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDrive(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.$store.dispatch('LoadDriveOption');
            });
          } else {
            addDrive(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.$store.dispatch('LoadDriveOption');
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(this.$store.state.message.delConfirm).then(function () {
        return delDrive(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
        this.$store.dispatch('LoadDriveOption');
      }).catch((res) => {
        this.loading = false;
        const list = res.data;
        if (list.length) {
          this.driveInUsedList = list;
          this.deleteFailedDialogVisible = true;
        }
        // console.log(list,'删除失败')
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const currentDate = this.parseTime(new Date());
      this.download('device/drive/export', {
        ...this.queryParams,
        exportBlank: '0'
      }, `驱动管理_${currentDate}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-select {
  width: 100%;
}
</style>
